<template>
    <el-container>
        <el-header>
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="团队">
                    <el-select-v2 size="small" v-model="formInline.teamid" filterable
                        :options="teams.map(e => { return { label: String(e.name), value: Number(e.ID) } })" />
                </el-form-item>
                <el-form-item label="时间">
                    <el-date-picker v-model="time" type="daterange" :shortcuts="shortcuts"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="start">查询</el-button>
                </el-form-item>
            </el-form>
        </el-header>
        <el-main>
            <div>
                <div class="text-center">
                    用户行为（按周）
                </div>
                <lineVue :data="tableData1" :height="500"></lineVue>
            </div>
            <div>
                <div class="text-center">
                    用户积分（按周）
                </div>
                <lineVue :data="tableData2" :height="500"></lineVue>
            </div>
        </el-main>
    </el-container>
</template>

<script setup lang="ts">
import FetchApi from '../../../logs/api';
import { compile, computed, onMounted, reactive, ref, watch } from 'vue'
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { useStore } from 'vuex';
import { Storekey } from '../../../interface';
import lineVue from '../../../components/antv/line.vue'
import moment from 'moment'
import { asyncselectstatistics, asyncselectteams, asyncselectteamuser, asyncselectuserchar, IselectstatisticsType, Iselectuserchar } from '../../../api';
import dayjs, { Dayjs } from 'dayjs';
import { dealy, shortcuts } from '../../../util/time';
import { forEach, groupBy, orderBy } from 'lodash-es';
import { publicDecrypt } from 'crypto';
import { object } from 'underscore';
type RangeValue = [Dayjs, Dayjs];





const date = dayjs()

const time = ref([new Date(Date.now() - 1000 * 60 * 60 * 24 * 365), new Date()])

const formInline = reactive<{
    teamid?: number
    userids?: number[],
    timetype: string
}>({
    timetype: '%x-%v'
})


const teams = ref<Array<Studycodemodel.Iteam>>([])
const getusers = ref<Array<Studycodemodel.Iuser>>([]);

const teamuser = ref<{ teamid: number, count: number }[]>([])

const teamlasttime = ref<{ teamid: number, count: number }[]>([])

const tableData = ref<{ type: keyof Iselectuserchar | 'video', count: number, day: string }[]>([])

const tableData1 = computed(() => {
    return tableData.value.filter(e => {
        return ['登录人数', '练题人数', '比赛人数', '提交题解人数', '提交讨论人数', '新注册人数', '注册人数', '观看视频人数'].includes(e.type)
    })
})

const tableData2 = computed(() => {
    return tableData.value.filter(e => {
        return ['获得比赛积分人数', '获得练习积分人数', '获得金币人数', '获得贡献积分人数'].includes(e.type)
    })
})


// 团队用户参加比赛次数


// 团队用户提交题目数量
const teamuserquestion = ref<{ teamid: number, count: number }[]>([])

// 团队所有用户观看视频次数
const teamvideo = ref<{ teamid: number, count: number }[]>([])

// 团队观看过视频人数
const teamuservideo = ref<{ teamid: number, count: number }[]>([])

async function getteamuservideo(): Promise<{ count: string, day: string }[]> {
    let query = '* and type:video'
    if (formInline.teamid) {
        query += `AND _teamids_:${formInline.teamid}`
    }
    const { data } = await FetchApi({
        from: dayjs(time.value[0]).toDate(),
        to: dayjs(time.value[1]).toDate(),
        query: query + `| select   date_format(__time__, '${formInline.timetype}') as day, count(DISTINCT(_userid_)) as count group by day order by day`,
        projectName: "htetest1",
        logstoreName: "ojhte",
        reverse: true
    })
    return data
}

async function getteam() {
    const { rows } = await asyncselectteams({
        _limit: 10000
    })
    teams.value = rows
}

async function selectquestion() {
    return asyncselectuserchar({
        starttime: dayjs(time.value[0]).toDate(),
        endtime: dayjs(time.value[1]).toDate(),
        ...formInline
    })
}


onMounted(async () => {
    await getteam()
    start()
})

async function start() {
    const data = await selectquestion()
    const _table: { type: keyof Iselectuserchar | 'video', count: number, day: string }[] = []
    // forEach(data, (v, k) => {
    //     forEach(v, (t) => {
    //         _table.push({
    //             count: t.count,
    //             day: t.day,
    //             type: k
    //         })
    //     })
    // })


    try {
        const video = await getteamuservideo()
        forEach(video, (t) => {
            _table.push({
                day: t.day,
                count: t.count,
                type: '观看视频人数'
            })
        })
    } catch (e) {

    }

    const table: { type: keyof Iselectuserchar | 'video', count: number, day: string }[] = []
    const num = dayjs(time.value[1]).diff(dayjs(time.value[0]), 'week')
    const key = Object.keys(data)
    console.log(num)

    for (let v = 0; v < num; v++) {
        const day = moment(time.value[0]).add(v, 'week').format('YYYY-ww')
        key.forEach(e => {
            const count = data[e].find((z: { day: string; }) => z.day === day)?.count || 0
            table.push({
                day,
                count,
                type: e
            })
        })
        const count = _table.find(z => z.day === day)?.count || 0
        table.push({
            day,
            count,
            type: '观看视频人数'
        })
    }
    tableData.value = table
}

watch(
    () => formInline.teamid,
    (n) => {
        if (n) {
            const team = teams.value.find((e) => e.ID === formInline.teamid);
            asyncselectteamuser({
                teamid: n,
            }).then((e) => {
                const { rows } = e;
                getusers.value = rows.map((v) => {
                    const { user, username } = v;
                    if (username && user) {
                        user.name = username;
                    }
                    return user;
                });
                if (team && team.user) {
                    getusers.value.push(team.user);
                }
                formInline.userids = getusers.value.map((v) => Number(v?.ID));
            });
        } else {
            getusers.value = [];
            formInline.userids = [];
        }
    }
);


watch(() => time.value, e => {
    const [a, b] = e
    const t = dayjs(a).diff(dayjs(b), 'minute')
    // if (t > 6) {
    //     formInline.timetype = '%Y-%W'
    // } else {
    //     formInline.timetype = '%Y-%m-%d'

    // }
})

</script>